package top.smallway.lightbandassistant_app.UI;

import static top.smallway.lightbandassistant_app.UI.MainActivity.loginManager;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.AppUtils;
import com.google.android.material.navigation.NavigationView;

import java.net.URISyntaxException;

import top.smallway.lightbandassistant_app.R;
import top.smallway.lightbandassistant_app.network.LoginManager;
import top.smallway.lightbandassistant_app.network.Okhttp;


/**
 * 个人中心Fragment
 * 负责显示用户个人信息、登录状态管理和各种功能入口
 * 包括版本检查、隐私政策、用户协议、登出和捐赠等功能
 */
public class Mine extends Fragment {
    // 用户头像ImageView
    private ImageView pic;
    // 当前应用版本号
    String version = AppUtils.getAppVersionName();
    // 个人信息区域布局
    private LinearLayout mine;
    // 底部导航菜单
    private NavigationView navigationView;
    // 用户ID文本显示
    public static TextView text_id;
    // 用户名文本显示
    public static TextView user_name;
    public static String android;
    // 相机权限请求码
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 200;

    /**
     * Handler消息处理
     * 主要处理版本检查结果：
     * case 0: 处理版本检查结果，如果是最新版本显示提示，否则跳转到下载页
     * case -1,-2,-3: 预留的错误处理
     */
    private final Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void dispatchMessage(@NonNull Message msg) {
            super.dispatchMessage(msg);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    JSONObject jsonObject = JSON.parseObject(msg.obj.toString());
                    String my_version = jsonObject.getString("version");
                    if (version.equals(my_version)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "当前为最新版本", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(jsonObject.getString("url")));
                        startActivity(browserIntent);
                    }
                    break;
                case -1:
                    break;
                case -2:

                    break;
                case -3:
                    break;
            }
        }
    };


    /**
     * Fragment创建时的初始化
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    /**
     * 创建Fragment视图
     * 初始化UI组件并检查登录状态
     * 根据登录状态更新用户信息显示
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_mine, container, false);
        initview(rootView);
        new Thread(new Runnable() {
            @Override
            public void run() {
                loginManager.checkLoggedIn(new LoginManager.LoginStatus() {
                    @Override
                    public void Logined(String username, String id, String email) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                user_name.setText(username);
                                text_id.setText("ID:" + id);
                            }
                        });
                    }

                    @Override
                    public void Unlogined() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                user_name.setText("登录/注册");
                                text_id.setText("登录以享受更多服务");
                                mine.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startActivity(new Intent(getContext(), Login.class));
                                    }
                                });
                            }
                        });


                    }
                });
            }
        }).start();


        return rootView;
    }

    /**
     * 处理权限请求结果
     * 主要处理相机权限的授权结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                Toast.makeText(getContext(), "Camera permission required", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 初始化视图组件
     * 设置底部导航菜单的点击事件处理：
     * - 版本检查
     * - 隐私政策
     * - 用户协议
     * - 登出功能
     * - 捐赠功能
     * - 我的收藏
     */
    private void initview(View rootView) {

        pic = rootView.findViewById(R.id.pic);
        navigationView = rootView.findViewById(R.id.bottomNavigationView);
        text_id = rootView.findViewById(R.id.id);
        user_name = rootView.findViewById(R.id.username);
        mine = rootView.findViewById(R.id.mine);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId(); // 获取选中的 MenuItem ID
                if (itemId == R.id.home_page) {
                    Message message = new Message();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            JSONObject jsonObject = Okhttp.GetVersion();
                            message.what = 0;
                            message.obj = jsonObject;
                            mHandler.sendMessage(message);
                        }
                    }).start();
//                  使用教程
                } else if (itemId == R.id.find_page) {
//                  隐私政策
                    Intent intent = new Intent(getContext(), YinSi.class);
                    startActivity(intent);
                } else if (itemId == R.id.my_page) {
//                  用户协议
                    Intent intent = new Intent(getContext(), UserAgreement.class);
                    startActivity(intent);
                } else if (itemId == R.id.item4) {
                    loginManager.logout();
                    user_name.setText("登录/注册");
                    text_id.setText("登录以享受更多服务");
                    mine.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(getContext(), Login.class));
                        }
                    });
//                  设置
                } else if (itemId == R.id.pay) {
//                  捐赠链接
                    String downloadUrl = "intent://platformapi/startapp?saId=10000007&" + "clientVersion=3.7.0.0718&qrcode=https%3A%2F%2Fqr.alipay.com%2Ffkx18377ukyddpcpqvemq61%3F_s" + "%3Dweb-other&_t=1472443966571#Intent;" + "scheme=alipayqr;package=com.eg.android.AlipayGphone;end";
                    Intent browserIntent = null;
                    try {
                        browserIntent = Intent.parseUri(downloadUrl, Intent.URI_INTENT_SCHEME);
                        startActivity(browserIntent);
                    } catch (ActivityNotFoundException | URISyntaxException e) {
                        Toast.makeText(getContext(), "未安装支付宝！", Toast.LENGTH_SHORT).show();
                    }

                } else if (itemId == R.id.star) {
                    Intent intent = new Intent(getContext(), MyStartActivity.class);
                    startActivity(intent);
                }
                return true;
            }
        });

    }


}